/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/*************************************************************************
 * File: mutex_pthread.h
 *************************************************************************
 *\author: starlove
 *************************************************************************/

#ifndef __MLSE_LIBRARY_MUTEX_PTHREAD_H__
#define __MLSE_LIBRARY_MUTEX_PTHREAD_H__

#include <pthread.h>

struct Mutex
{
	Mutex()
	{
		pthread_mutex_init(&mtx,NULL);
	}

	~Mutex()
	{
		pthread_mutex_destroy( &mtx );
	}

	inline void lock()
	{
		pthread_mutex_lock( &mtx );
	}

	inline void unlock()
	{
		pthread_mutex_unlock( &mtx );
	}
	pthread_mutex_t mtx;
};

class CSemiAutoIntLock
{
public:
	void lock()
	{
		m_mtx.lock();
	}

	void unlock()
	{
		m_mtx.unlock();
	}
protected:
	Mutex m_mtx;
};

template<class T>
class CLocker
{
public:
	CLocker(T &locker) : m_locker(locker)
	{
		m_locker.lock();
	}
	~CLocker()
	{
		m_locker.unlock();
	}
	void lock()
	{
		m_locker.lock();
	}

	void unlock()
	{
		m_locker.unlock();
	}
protected:
	T &m_locker;
};
#define MUTEX() \
  lock()

#define CLEAR_MUTEX() \
  unlock()

#define AUTO_MUTEX( KEY,  mtx ) \
  CLocker<CSemiAutoIntLock> KEY(mtx)

#define AUTO_SELF_MUTEX(KEY) \
  CLocker<CSemiAutoIntLock> KEY(*this)

#define CLEAR_AUTO_SELF_MUTEX(KEY) \
  KEY.unlock()

#endif // __MLSE_LIBRARY_MUTEX_PTHREAD_H__
